package com.itg.vms.servlet;

import com.itg.vms.entity.User;
import com.itg.vms.service.LogService;
import com.itg.vms.service.UserService;
import com.itg.vms.service.impl.LogServiceImpl;
import com.itg.vms.service.impl.UserServiceImpl;
import com.mchange.v2.c3p0.impl.IdentityTokenResolvable;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author itg
 * @create 2023年03月06日 14:41:44
 */
@WebServlet("/login")
public class LoginServlet extends BaseServlet {

    /**
     * 创建业务层对象
     */
    UserService userService = new UserServiceImpl();

    /**
     * 创建日志业务层对象
     */
    LogService logService = new LogServiceImpl();

    /**
     * 管理员用户登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        //获取前台传来的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //获取前台传来的验证码
        String VCode = req.getParameter("captcha");
        //获取前台用户是否勾选记住密码
        String rememberMe = req.getParameter("rememberMe");

        //将验证码转为大写
        VCode = VCode.toUpperCase();
        //获取后台session中的验证码
        String code = (String) req.getSession().getAttribute("code");

        //判断验证码是否输入正确
        if (!code.equals(VCode)) {
            resp.getWriter().write(error("验证码输入错误"));
        } else {
            //调用业务层方法查询管理员的对象
            User user = userService.login(username, password);
            if (user != null) {
                System.out.println("登录成功");
                //user数据写入到session中
                req.getSession().setAttribute("loginUser", user);
                //存入日志
                logService.addLog(user.getUserId(), "用户登录", req.getRemoteAddr());
                //创建cookie
                Cookie cookie1 = new Cookie("username", username);
                Cookie cookie2 = new Cookie("password", password);
                //设置cookie作用域范围
                cookie1.setPath("/");
                cookie2.setPath("/");

                //逻辑，用户勾选了记住密码
                if ("true".equals(rememberMe)) {
                    //设置cookie有效期
                    cookie1.setMaxAge(60 * 60 * 24 * 7);
                    cookie2.setMaxAge(60 * 60 * 24 * 7);

                } else {
                    // 设置cookie过期
                    cookie1.setMaxAge(0);
                    cookie2.setMaxAge(0);
                }
                //向浏览器发送cookie
                resp.addCookie(cookie1);
                resp.addCookie(cookie2);

                //响应json数据
                resp.getWriter().write(success(user));
            } else {
                //响应json数据
                System.out.println("登录失败");
                resp.getWriter().write(error("账号或密码错误"));
            }
        }

        System.out.println(username + "----" + password);
    }

    /**
     * 退出登录方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将用户保存在session作用域中的user对象删除
        HttpSession session = req.getSession();
        session.removeAttribute("loginUser");
        //设置cookie过期
        Cookie[] cookies = req.getCookies();
        Cookie cookie1 = null;
        Cookie cookie2 = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //System.out.println(cookie.getName()+"-->"+cookie.getValue());
                if ("username".equals(cookie.getName())) {
                    cookie1 = cookie;
                    cookie1.setMaxAge(0);
                } else if ("password".equals(cookie.getName())) {
                    cookie2 = cookie;
                    cookie2.setMaxAge(0);
                }
            }
            if (cookie1 != null && cookie2 != null) {
                resp.addCookie(cookie1);
                resp.addCookie(cookie2);
            }
        }
        resp.sendRedirect("login.html");
    }

    /**
     * 用户注册方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String nick_name = req.getParameter("nick_name");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String phoneNumber = req.getParameter("phoneNumber");

        User user = new User();
        user.setUserName(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        user.setNickName(nick_name);
        //调用业务层方法进行注册
        Integer b = userService.registerUser(user);
        if (b==1) {
            resp.getWriter().write(success("注册成功，请登录"));
        } else if(b==0){
            resp.getWriter().write(error("当前用户名已存在"));
        }else{
            resp.getWriter().write("貌似您的网络不太好！");
        }
    }
}
